package com.pipayshop.filter;

import com.pipayshop.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果handler不是方法，直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }


        // 获取请求中的token
        String token = request.getHeader("token");

        try {
            log.info("jwt校验:{}", token);
            // 解析JWT
            Claims claims = JwtUtil.parseJWT(token);
            // 如果需要，可以将claims存储在请求中，后续可用于鉴权
            return true;
        } catch (Exception ex) {
            response.setStatus(401);
            return false;
        }
    }
}
